<template>

  <div style="margin:40px;">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="margin:0;font-size:18px;font-weight:bold;">{{ this.$route.meta.title }}</span>
        <el-button style="float: right; padding:3px 0" type="text" @click="cancelForm">返回列表</el-button>
      </div>
      <div style="width:600px;">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item
            label="用户名"
            prop="username"
          >
            <el-input
              v-model="form.username"
            />
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
          >
            <el-input
              v-model="form.password"
            />
          </el-form-item>
          <el-form-item
            label="姓名"
            prop="fullName"
          >
            <el-input
              v-model="form.fullName"
            />
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="form.sex" style="width: 178px">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model.number="form.mobile" />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="form.status" style="width: 178px">
              <el-radio :label="1">激活</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="单位">
            <el-input v-model="dept" readonly />
            <!--          <treeselect-->
            <!--            :multiple="true"-->
            <!--            :flat="true"-->
            <!--            v-model="form.deptIdList"-->
            <!--            :options="depts"-->
            <!--            placeholder="选择单位"-->
            <!--          />-->
          </el-form-item>
          <el-form-item label="角色" prop="roleIdList">
            <el-select
              v-model="form.roleIdList"
              multiple
              placeholder="请选择"
              style="width:100%;"
            >
              <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="text"
              @click="cancelForm"
            >
              取消
            </el-button>
            <el-button
              :loading="loading"
              type="primary"
              @click="submitForm"
            >
              确认
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

  </div>
</template>

<script>
import { isvalidPhone } from '@/utils/validate'
import crudUser from '@/api/sys/user'
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { list_to_vuetree } from '@/utils'
import { getRoleList } from '@/api/sys/role'
import { getDeptList } from '@/api/sys/dept'

const defaultForm = {
  userId: null,
  username: '',
  password: '',
  fullName: '',
  email: null,
  mobile: null,
  sex: 1,
  status: 1,
  roleIdList: [],
  deptIdList: [],
  roles: [],

}

export default {
  components: {
    Treeselect
  },

  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    deptId: {
      type: Number,
      default: -1
    }
  },
  data() {
    // 自定义验证
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback()
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        fullName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        mobile: [
          { trigger: 'blur', validator: validPhone }
        ]
      },
      depts: [],
      roles: [],
      form: defaultForm,
      loading: false,
      dept: ''
    }
  },
  created() {
    console.log(this.deptId)
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
    getDeptList().then(res => {
      const list = res.data.list.filter(item => item.deptId == this.deptId)
      this.dept = list[0].name
      this.form.deptId = this.deptId
      // this.depts=list_to_vuetree(res.data.list,'deptId','name')
    })
    getRoleList().then(res => {
      const roleList = [];
      for (let i = 0; i < res.data.list.length; i++) {
        const item = res.data.list[i];
        const role = { id: item.roleId, name: item.roleName };
        roleList.push(role);
      }
      this.roles = roleList;
    });
  },
  methods: {
    fetchData(id) {
      crudUser.get(id).then(response => {
        this.form = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    cancelForm() {
      this.$router.push('/sys/dept')
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) { return }
        this.loading = true;
        if (this.isEdit) {
          crudUser.edit(this.form).then(() => {
            this.$notify({
              title: '成功',
              message: '修改用户成功',
              type: 'success',
              duration: 2000
            })
            this.loading = false
            this.cancelForm()
          })
        } else {
          crudUser.add(this.form).then(() => {
            this.$notify({
              title: '成功',
              message: '新增用户成功',
              type: 'success',
              duration: 2000
            })
            this.loading = false
            this.cancelForm()
          })
        }
      })
    }

  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
</style>
